<template>
  <!-- 头部信息 -->
  <HeaderView title="地址管理" :hasBack='true' path="mine"/>

  <van-address-list
    v-model="chosenAddressId"
    :list="list"
    default-tag-text="默认"
    @add="onAdd"
    @edit="onEdit"
    @select="selectAddress"
  />

  <!-- 时间超时 -->
  <TimeOutView v-if="timeFlag"/>
</template>

<script lang="ts" setup>
import HeaderView from '@/components/Header/IndexView.vue'
import TimeOutView from '@/components/TimeOut/IndexView.vue'
import { GetAddress, DefaultAddressFnc } from '@/api/address'
import { GetAddressListType } from '@/type/address'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'

import { ref, onMounted } from 'vue'
const timeFlag = ref(false) // 请求超时 显示界面
const list = ref([]) // 地址列表
const chosenAddressId = ref('0')
const router = useRouter()

// 数据初始化
const init = async () => {
  const res = await GetAddress().catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') timeFlag.value = true
  })

  try {
    if (res?.status === 200) {
      // 勾选默认地址 有可能没有默认地址  有可能有
      if (res.data.data.filter((item: {is_default: number}) => item.is_default === 1).length !== 0) {
        chosenAddressId.value = res.data.data.filter((item: {is_default: number}) => item.is_default === 1)[0].id
      }
      list.value = res.data.data.map((item: GetAddressListType) => {
        return {
          id: item.id,
          name: item.name,
          tel: item.phone,
          address: `${item.province} ${item.city} ${item.county} ${item.address.split('-')[0]}`,
          isDefault: !!item.is_default
        }
      })
    }
  } catch (error) {
    console.log(error)
  }
}

onMounted(() => {
  init()
})

// 新增地址
const onAdd = () => {
  router.push({ path: '/editAddress', query: { type: 'add' } })
}

// 修改地址
const onEdit = (item: {id: number}) => {
  router.push({ path: 'editAddress', query: { type: 'edit', id: item.id } })
}

// 更改默认地址
const selectAddress = async (item: {id: number}) => {
  const res = await DefaultAddressFnc(item.id).catch(err => {
    if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
      showToast({ type: 'fail', message: '请稍后再试', duration: 1500, forbidClick: true })
    }
  })

  try {
    if (res?.status === 204) {
      showToast({ message: '更新成功', duration: 1000, onClose: () => init() })
    }
  } catch (error) {
    console.log(error)
  }
}

</script>
<style lang="scss" scoped>
:deep .van-radio-group{
  margin-top: 50px
}
</style>
